#include <iostream>
#include <string>
#include <cstdio>
#include <pthread.h>
#include <unistd.h>
#include <thread>

void showtid(pthread_t &tid)
{
    printf("tid: %0x%lx\n", tid);
}

std::string FormatId(const pthread_t &tid)
{
    char id[64];
    snprintf(id, sizeof(id), "0x%lx", tid);
    return id;
}

void *routine(void *args)
{
    std::string name = static_cast<const char *>(args);
    pthread_t tid = pthread_self();
    int cnt = 5;
    while (cnt)
    {
        std::cout << "我是一个新线程：我的名字是：" << name << "我的ID是：" << FormatId(tid) << std::endl;
        sleep(1);
        cnt--;
    }
    return nullptr;
}

int main()
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, routine, (void *)"thread-1");
    (void)n;

    int cnt = 5;
    while (cnt)
    {
        std::cout << "我是一个main线程：我的名字是：main thread"  << "我的ID是：" << FormatId(pthread_self()) << std::endl;
        sleep(1);
        cnt--;
    }

    showtid(tid);

    pthread_join(tid, nullptr);
    return 0;
}

/*void hello()
{
    while(true)
    {
        std::cout<<"新线程：hello world ,pid:"<<getpid()<<std::endl;
        sleep(1);
    }
}

int main()
{
   std::thread t(hello);
    while(true)
    {
        std::cout<<"我是主线程...."<<"，pid:"<<getpid()<<std::endl;
        sleep(1);
    }
    t.hoin();
    return 0;
}

/*void *threadrun(void *args)
{
    std::string name=(const char*)args;
    while(true)
    {
        std::cout<<"我是新线程：name:"<<name<<"，pid:"<<getpid()<<std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid,nullptr,threadrun,(void*)"thread-1");

    while(true)
    {
        std::cout<<"我是主线程...."<<"，pid:"<<getpid()<<std::endl;
        sleep(1);
    }
    return 0;
}*/